package com.ming.closeto.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.ming.closeto.R;
import com.ming.closeto.adapter.FileBrowseAdapter;
import com.ming.closeto.base.BaseActivity;
import com.ming.closeto.model.FileBrowseModel;
import com.ming.closeto.utils.CompareUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileBrowseActivity extends BaseActivity {

    private RecyclerView mRecyclerView;
    private FileBrowseAdapter mFileBrowseAdapter;
    private List<FileBrowseModel> mList = new ArrayList<>();

    // 根目录
    private static final String basePath = "/sdcard";

    private String [] items = { "复制","移动", "属性", "删除"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_br);
        initView();
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mFileBrowseAdapter = new FileBrowseAdapter(this, mList);
        mRecyclerView.setAdapter(mFileBrowseAdapter);

        // 读取文件列表
        getFileData(basePath);

        mFileBrowseAdapter.setOnItemClickListener(new FileBrowseAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                /**
                 * 判断当前是否是文件夹
                 * 如果是文件夹，那么切换到对应文件夹
                 * 如果是文件 就 open file
                 */
                FileBrowseModel model = mList.get(position);
                String title = model.getTitle();
                String path = model.getPath();
                int icon = model.getIcon();

                // 更新列表

                // 判断文件夹与文件的方法  ... 通过设置的 icon 图标
                if (icon == R.drawable.icon_system_folder) {
                    // 是文件夹
                    getFileData(path);
                } else {
                    // 文件
                    openFile(title, path);
                }
            }

            @Override
            public void onLongClick(int position) {
                // 额外功能
                new AlertDialog.Builder(FileBrowseActivity.this)
                        .setTitle("设置")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(FileBrowseActivity.this, items[which], Toast.LENGTH_SHORT).show();

                                /**
                                 *  删除文件方法
                                 *  File file = new File(path);
                                 *  file.delete();
                                 */
                            }
                        }).show();
            }
        });
    }


    /**
     * 打开文件
     * @param title
     * @param path
     */
    private void openFile(String title, String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (title.endsWith(".apk")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        } else if (title.endsWith(".ppt")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.ms-powerpoint");
        } else if (title.endsWith(".zip")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/x-gzip");
        } else if (title.endsWith(".rar")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/x-gzip");
        } else if (title.endsWith(".doc")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/msword");
        } else if (title.endsWith(".txt")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "text/plain");
        } else if (title.endsWith(".mp3")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "audio/*");
        } else if (title.endsWith(".mp4")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "video/*");
        } else if (title.endsWith(".pdf")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/pdf");
        } else if (title.endsWith(".execl")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.ms-excel");
        } else if (title.endsWith(".png")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
        } else if (title.endsWith(".jpg")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
        } else if (title.endsWith(".java")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "text/plain");
        } else if (title.endsWith(".c")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "text/plain");
        } else if (title.endsWith(".py")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "text/plain");
        } else if (title.endsWith(".json")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "text/plain");
        } else if (title.endsWith(".html")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "text/html");
        } else if (title.endsWith(".gif")) {
            intent.setDataAndType(Uri.fromFile(new File(path)), "image/gif");
        } else {
            //未知类型
            Toast.makeText(this, "未知File Type", Toast.LENGTH_SHORT).show();
        }

        startActivity(intent);
    }

    /**
     * 读取制定目录下的文件
     * @param path
     */
    private void getFileData(String path) {
        getSupportActionBar().setTitle(path);
        // 为了防止数据重复
        if (mList != null) {
            if (mList.size() > 0) {
                mList.clear();
            }
        }

        File file = new File(path);
        // 读取当前目录下的文件
        File[] files = file.listFiles();
        if (files != null) {
            // 遍历
            for (int i=0; i<files.length; i++) {
                FileBrowseModel model = new FileBrowseModel();

                String title = files[i].getName();
                String paths = files[i].getPath();
                boolean isDirectory = files[i].isDirectory();

                model.setTitle(title);
                model.setPath(paths);

                // 判断是否是文件夹
                if (isDirectory) {
                    model.setIcon(R.drawable.icon_system_folder);
                } else {
                    // 如果不是文件夹，判断后缀,配图标
                    parsingEnd(title, model);
                }
                mList.add(model);
            }
        }
        // 排序
        Collections.sort(mList, new CompareUtils());
        // 文件处理完成之后  在每一个页面上增加一个返回上一页的操作
        // 判断是否为根目录， 根目录不需要返回上一页的操作
        if (!path.equals(basePath)) {
            FileBrowseModel model = new FileBrowseModel();
            model.setTitle("返回上一页/");
            model.setPath(file.getParent());
            getSupportActionBar().setTitle(file.getParent());
            model.setIcon(R.drawable.icon_system_folder);
            mList.add(0, model);
        } else {
            getSupportActionBar().setTitle(basePath);
        }
        // 刷新适配器
        mFileBrowseAdapter.notifyDataSetChanged();
    }

    /**
     * 判断文件类型
     * @param title
     * @param model
     */
    private void parsingEnd(String title, FileBrowseModel model) {
        if (title.endsWith(".zip")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".apk")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".txt")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".mp3")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".mp4")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".pdf")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".doc")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".ppt")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".jpg")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".png")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".java")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".c")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".html")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".json")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else if (title.endsWith(".log")) {
            model.setIcon(R.mipmap.ic_launcher);
        } else {
            //未知文件
            model.setIcon(R.mipmap.ic_launcher);
        }
    }


}
